addDragEventHandler();
initPriorityTable();
initLocatorsSort();
initButtonMethod();

var locatorsDefaultValues = {
    "ui": 0,
    "id": 1,
    "link": 2,
    "name": 3,
    "dom:name": 4,
    "xpath:link": 5,
    "xpath:img": 6,
    "xpath:attributes": 7,
    "xpath:idRelative": 8,
    "xpath:href": 9,
    "dom:index": 10,
    "xpath:position": 11,
    "css": 12,
    "xpath:neighbor": 13,
    "xpath:class:text": 14,
    "xpath:label:text": 15,
    "xpath:class": 16
};
var locatorsDescs = {
    "ui": "不清楚,反正是第一个",
    "id": "有id属性,根据id定位",
    "link": "标签名为a,根据标签中文字定位",
    "name": "有name属性,根据name定位",
    "dom:name": "有form并且有name属性,根据这两个属性定位",
    "xpath:link": "标签名为a,使用xpath定位包含特定文字的a标签",
    "xpath:img": "标签名为img,使用xpath分别尝试根据alt、title、src属性定位img标签",
    "xpath:attributes": "使用xpath根据id、name、value、type、action、onclick这些属性定位",
    "xpath:idRelative": "使用xpath根据id和临近标签定位",
    "xpath:href": "使用xpath根据href属性标签定位",
    "dom:index": "看情况是form标签下的元素下标",
    "xpath:position": "使用xpath绝对位置定位",
    "css": "使用css定位",
    "xpath:neighbor": "ku-locatorBuilders.js里独有的,说的是从前面和后面的邻居开始的xpath（用xpath=（@param2）连接）",
    "xpath:class:text": "根据最后标签的class和textContent以及之前父标签的标签名和class属性定位",
    "xpath:label:text": "如果元素向上找5层父元素可以找到label并且label有text内容,则尝试使用label相对位置定位",
    "xpath:class": "根据标签名和class内容定位元素,如果是唯一的则使用xpath定位,如果没有class或者不是唯一的则不用这个"
};

var currentPriority = "";
var currentlocatorsSort = "false";

function changePriorityTable() {
    var tableId = document.getElementById("records-grid");
    var strs = new Array();
    for (var i = 0; i < tableId.rows.length; i++) {
        //console.log(tableId.rows[i].cells[0].innerHTML);
        strs.push(tableId.rows[i].cells[0].innerHTML);
    }
    currentPriority = strs.toString();
    //console.log(strs.toString());
    //setKatalonLocatorsPriority(strs.toString());
}


function initPriorityTable() {
    var prioritytemp = "";
    getKatalonLocatorsPriority(function(test) {
        prioritytemp = test;
        if (prioritytemp != "") {

            var strs = new Array();
            strs = prioritytemp.split(",");
            for (i = 0; i < strs.length; i++) {
                var tr = "<tr><td>" + strs[i] + "</td><td>" + locatorsDescs[strs[i]] + "</td><td>" + locatorsDefaultValues[strs[i]] + "</td></tr>"
                $("#records-grid").append(tr);
            }
            currentPriority = test;
        }
    });
}

function initLocatorsSort() {

    var isSort = false;
    getIsKatalonLocatorsSort(function(test) {
        isSort = test;
        if (isSort != "") {
            if (isSort) {
                $("#save-locators-sort-true").attr("checked", true);
            } else {
                $("#save-locators-sort-false").attr("checked", true);
            }
        } else {
            $("#save-locators-sort-false").attr("checked", true);
        }
    });
}


function addDragEventHandler() {
    //绑定事件
    var addNewEvent = document.addEventListener ? function(el, type, callback) {
        el.addEventListener(type, callback, !1);
    } : function(el, type, callback) {
        el.attachEvent("on" + type, callback);
    }
    //移除事件
    var removeNewEvent = document.removeEventListener ? function(el, type, callback) {
        el.removeEventListener(type, callback);
    } : function(el, type, callback) {
        el.detachEvent("on" + type, callback);
    }
    //精确获取样式
    var getNewStyle = document.defaultView ? function(el, style) {
        return document.defaultView.getComputedStyle(el, null).getPropertyValue(style)
    } : function(el, style) {
        style = style.replace(/\-(\w)/g, function($, $1) {
            return $1.toUpperCase();
        });
        return el.currentStyle[style];
    }
    var dragManager = {
        clientY: 0,
        draging: function(e) { //mousemove时拖动行
            var dragObj = dragManager.dragObj;
            if (dragObj) {
                e = e || event;
                if (window.getSelection) { //w3c
                    window.getSelection().removeAllRanges();
                } else if (document.selection) {
                    document.selection.empty(); //IE
                }
                var y = e.clientY;
                var down = y > dragManager.clientY; //是否向下移动
                var tr = document.elementFromPoint(e.clientX, e.clientY);
                if (tr && tr.nodeName == "TD") {
                    tr = tr.parentNode
                    dragManager.clientY = y;
                    if (dragObj !== tr) {
                        tr.parentNode.insertBefore(dragObj, (down ? tr.nextSibling : tr));
                    }
                };
            }
        },
        dragStart: function(e) {
            e = e || event;
            var target = e.target || e.srcElement;
            if (target.nodeName === "TD") {
                target = target.parentNode;
                dragManager.dragObj = target;
                if (!target.getAttribute("data-background")) {
                    var background = getNewStyle(target, "background-color");
                    target.setAttribute("data-background", background)
                }
                //显示为可移动的状态
                target.style.backgroundColor = "  #ccc";
                target.style.cursor = "move";
                dragManager.clientY = e.clientY;
                addNewEvent(document, "mousemove", dragManager.draging);
                addNewEvent(document, "mouseup", dragManager.dragEnd);
            }
        },
        dragEnd: function(e) {
            var dragObj = dragManager.dragObj
            if (dragObj) {
                e = e || event;
                var target = e.target || e.srcElement;
                if (target.nodeName === "TD") {
                    target = target.parentNode;
                    dragObj.style.backgroundColor = dragObj.getAttribute("data-background");
                    dragObj.style.cursor = "default";
                    dragManager.dragObj = null;
                    removeNewEvent(document, "mousemove", dragManager.draging);
                    removeNewEvent(document, "mouseup", dragManager.dragEnd);
                }
            }
            changePriorityTable();
        },
        main: function(el) {
            addNewEvent(el, "mousedown", dragManager.dragStart);
        }
    }
    var el = document.getElementById("set-priority-grid");
    dragManager.main(el);
};

function resetPriorityTable() {
    var prioritytemp = "ui,id,link,name,dom:name,xpath:link,xpath:img,xpath:attributes,xpath:idRelative,xpath:href,dom:index,xpath:position,css,xpath:neighbor,xpath:class:text,xpath:label:text,xpath:class";
    var strs = new Array();
    $("#records-grid").html('');
    strs = prioritytemp.split(",");
    for (i = 0; i < strs.length; i++) {
        var tr = "<tr><td>" + strs[i] + "</td><td>" + locatorsDescs[strs[i]] + "</td><td>" + locatorsDefaultValues[strs[i]] + "</td></tr>"
        $("#records-grid").append(tr);
    }
    currentPriority = prioritytemp;
}

function initButtonMethod() {
    $("#save-priority").click(function() {
        if (currentPriority != "") {
            setKatalonLocatorsPriority(currentPriority);
            alert("保存成功,请刷新待录制页面生效");
        } else {
            alert("保存失败");
        }
    })
    $("#restore-priority").click(function() {
        resetPriorityTable()
        setKatalonLocatorsPriority(currentPriority);
        alert("重置成功,请刷新待录制页面生效");
    })
    $("#save-locators-sort-true").click(function() {
        currentlocatorsSort = "true";
    })
    $("#save-locators-sort-false").click(function() {
        currentlocatorsSort = "false";
    })
    $("#save-locators-sort").click(function() {
        setIsKatalonLocatorsSort(currentlocatorsSort);
        alert("设置成功,请刷新待录制页面生效");
    })
}